import {useState,useEffect} from 'react'
import {Table,Space,Tag,Button,message} from 'antd'
import {scanQRCodePay} from '../helpers'
import api from '../api'

interface IProduct {
  id:string
  name:string
  cover:string
  price:number
}


function Orders(){
  const [orders,setOrders] = useState([])
  const fetchOrders = ()=>{
    api.get('/orders').then(response=>{
      setOrders(response.data)
    }).catch(error=>{
      console.log("获取订单失败:",error)
      message.error('获取订单失败');
    })
  }

  const closeOrder = (id:string)=>{
    api.get(`/payment/order/${id}/close`).then(()=>{
      message.success('订单已关闭')
      fetchOrders()
    }).catch(error=>{
      console.log("关闭订单失败:",error)
      message.error('关闭订单失败');
    
    })
  }

  useEffect(fetchOrders,[])
  const columns = [
    {
      title:"订单编号",dataIndex:"id",key:"id"
    },
    {
      title:"产品",dataIndex:"product",key:"product",render:(product:IProduct)=> product.name
    },
    {
      title:"总费用",dataIndex:"totalFee",key:"totalFee",render:(totalFee:number)=>"￥" + (totalFee / 100).toFixed(2)
    },
    {
      title:"状态",dataIndex:"orderStatus",key:"orderStatus",render:(text:string)=>{
        switch(text){
          case "PAID": return <Tag color={'green'}>支付成功</Tag>;
          case "UN_PAID": return <Tag color={'blue'}>未支付</Tag>;
          case "CLOSE_PID": return <Tag color={'red'}>已关闭</Tag>;
          default: return <Tag color={'warning'}>{text}</Tag>;
        }
      }
    },
    {
      title:"操作",key:"action",render:(_:any,rencord:any)=>{
        if(rencord.orderStatus === "UN_PAID"){
          return (
            <Space>
              <Button type='primary' onClick={()=>scanQRCodePay({
                orderNo: rencord.id,
                code_url:rencord.code_url,
                callback:()=>{
                  fetchOrders()
                }
              
              })}>继续支付</Button>
              <Button danger onClick={()=>closeOrder(rencord.id)}>关闭订单</Button>
            </Space>
          )
        }else{
          return null
        }
      }
    }
  ]
  return (
    <div>
      <Table columns={columns} dataSource={orders} rowKey='id'></Table>
    </div>
  )
}


export default Orders